package fr.toto.subtitles;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Download {

	public static synchronized void downloadfile(String url, String dest)
			throws Exception {
		Files.createDirectories(Paths.get(dest).getParent());
		Files.deleteIfExists(Paths.get(dest));

		URL server = new URL(url);
		HttpURLConnection.setFollowRedirects(true);
		HttpURLConnection connection = (HttpURLConnection) server
				.openConnection();
		connection.connect();

		while (connection.getResponseCode() == 302
				&& connection.getHeaderField("location") != null) {
			URL server2 = new URL(connection.getHeaderField("location"));
			connection = (HttpURLConnection) server2.openConnection();
			connection.connect();
		}
		InputStream in = connection.getInputStream();
		Files.copy(in, Paths.get(dest));
		in.close();

	}
}
